package com.shaokel.eduservice.controller;

import com.shaokel.commonutils.ReturnResult;
import com.shaokel.eduservice.client.VodClient;
import com.shaokel.eduservice.entity.EduVideo;
import com.shaokel.eduservice.service.EduVideoService;
import com.shaokel.exception.shaokelException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * 课程视频 前端控制器
 *
 * @author 少丶客
 * @since 2020-06-04
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient vodClient;

    //添加小节
    @PostMapping("/addVideo")
    public ReturnResult addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return ReturnResult.ok();
    }

    //修改小节
    @PostMapping("/updateVideo")
    public ReturnResult updateVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.updateById(eduVideo);
        return ReturnResult.ok();
    }

    //根据id查询
    @GetMapping("/getVideoInfo/{id}")
    public ReturnResult getVideoInfo(@PathVariable String id){
        EduVideo video = eduVideoService.getById(id);
        return ReturnResult.ok().data("video",video);
    }

    //删除小节
    @DeleteMapping("/{id}")
    public ReturnResult deleteVideo(@PathVariable String id){
        //根据小结id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //根据视频id，远程调用实现视频删除
        if(!StringUtils.isEmpty(videoSourceId)){
            ReturnResult returnResult = vodClient.removeAlyiVideo(videoSourceId);
            if(returnResult.getCode()==20001){
                throw new shaokelException(20001,"删除视频失败,熔断器");
            }
        }
        //删除小节
        eduVideoService.removeById(id);
        return ReturnResult.ok();
    }

}

